package com.fbty.base.dwr;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.directwebremoting.WebContextFactory;

import com.fbty.mt.domain.User;
import com.fbty.mt.exception.MtRuntimeException;



/**
 * @author chenrong
 */
public class DwrAuthHelper {
	/**
	 * 设置当前session用户,用于系统登录
	 * 
	 * @param user
	 *            当前session用户
	 */
	public static void setUser(Object emp) {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.setAttribute("login", emp);
	}

	/**
	 * 获取当前session用户
	 * 
	 * @return 当前session用户
	 */
	public static User getUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		User user = (User)session.getAttribute("user");
		if(user!=null){
			return user;
		}else {
			throw new MtRuntimeException("登录超时，请重新登录");
		}
	}
	
	
	/**
	 * 获取当前session ID
	 * 
	 * @return
	 */
	public static String getSessionId() {
		HttpSession session = WebContextFactory.get().getSession(true);
		return session.getId();
	}
	/**
	 * 获取当前session
	 * 
	 * @return
	 */
	public static HttpSession getSession() {
		return WebContextFactory.get().getSession();
	}
	/**
	 * 清除当前session用户
	 */
	public static void removeUser() {
		HttpSession session = WebContextFactory.get().getSession(true);
		session.removeAttribute("login");
	}

	/**
	 * 获取远程用户ipaddress
	 */
	public static String getIpAddress() {
		HttpServletRequest request = WebContextFactory.get().getHttpServletRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip != null) {
			String[] ips = ip.split(",");
			for (String o : ips) {
				if (!o.equals("unknown")) {
					return o;
				}
			}
		} else {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * The session key
	 */
	private static final String USER = "com.cqcis.ecsc.web.USER";
	private static final String LOGINID = "com.cqcis.ecsc.web.LOGINID";
	private static final String LOGINIP = "com.cqcis.ecsc.web.LOGINIP";
}
